<template>
	<div class='tags-input'>
		<el-tag
			v-for="(tag,i) in projectTags"
			:key="tag"
			class="tag"
			closable
			size="large"
			@close="onCloseTag(i)"
		>
			{{ tag }}
		</el-tag>
		<el-input
			v-if="tagInputting"
			class="tag"
			style="width: 220px;"
			placeholder="新标签，按回车或取消聚焦后确认"
			v-model="tagInputVal"
			@keyup.enter="onInputNewTag"
			@blur="onInputNewTag();tagInputting=false"
		/>
		<el-button
			v-else
			class="tag"
			@click="tagInputting=true"
		>
			添加标签
		</el-button>
	</div>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits } from 'vue'
import { computed } from '@vue/reactivity'

const props = defineProps<{
  tags: string, // 字符串tag
  splitKey: string, // 分割符号
}>()

const emit = defineEmits<{
  (e: 'changeTag', val: string): void
}>()
const projectTags = computed(() => props.tags.split(props.splitKey).filter(tag => tag))
const tagInputting = ref(false)
const tagInputVal = ref('')

const onInputNewTag = () => {
  if (!tagInputVal.value) {
    return
  }
  const tags = projectTags.value.concat(tagInputVal.value).join(props.splitKey)

  tagInputVal.value = ''
  emit('changeTag', tags)
}
const onCloseTag = (i:number) => {
  const tags = projectTags.value.slice(0, i).concat(projectTags.value.slice(i + 1)).join(props.splitKey)

  emit('changeTag', tags)
}

</script>

<style lang="scss" scoped>
.tags-input {
  .tag {
    margin-right: 10px;
  }
}
</style>
